package Tree;

import java.util.ArrayList;
import java.util.List;

public class TraversalByRecursion {
    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(1);
        node1.right = new TreeNode(2);
        node1.right.left = new TreeNode(3);
        TraversalByRecursion solution = new TraversalByRecursion();
        System.out.println(solution.preorderTraversal(node1));
    }
    //前序遍历，递归法
    public List<Integer> preorderTraversal(TreeNode root){
        List<Integer> result = new ArrayList<>();
        preorder(root,result);
        return result;
    }
    public void preorder(TreeNode node, List<Integer> list){
        if(node == null) return;
        list.add(node.val);
        preorder(node.left,list);
        preorder(node.right,list);
    }

    //中序遍历，递归法
    public List<Integer> inorderTraversal(TreeNode root){
        List<Integer> result = new ArrayList<>();
        inorder(root,result);
        return result;
    }
    public void inorder(TreeNode node, List<Integer> list){
        if(node == null) return;
        inorder(node.left,list);
        list.add(node.val);
        inorder(node.right,list);
    }

    //后序遍历，递归法
    public List<Integer> postorderTraversal(TreeNode root){
        List<Integer> result = new ArrayList<>();
        postorder(root,result);
        return result;
    }
    public void postorder(TreeNode node, List<Integer> list){
        if(node == null) return;
        postorder(node.left,list);
        postorder(node.right,list);
        list.add(node.val);
    }
}
